import { ref } from 'vue'
export const useWebsocket = () => {
  // 连接服务器
  // 执行完本语句,客户端就会与服务器进行连接。
  const localuser = JSON.parse(localStorage.getItem('user')) //从本地获取token
  const Authorization = localuser.userInfo.dataOne
  var ws = new WebSocket('wss://5987g53p36.zicp.fun/websocket/username', [
    Authorization
  ])
  const open = (ws.onopen = function (evt) {
    console.log('websockt连接成功')
    // ws.send("Hello WebSockets!");//send函数
  })
  const friendMessage = ref([])
  const message = (ws.onmessage = function (evt) {
    // console.log(JSON.parse(evt.data));
    friendMessage.value.push(JSON.parse(evt.data))
    console.log(friendMessage.value.push(JSON.parse(evt.data)));
    // localStorage.setItem('chatContentRecv', JSON.stringify(friendMessage.value))
  })

  // const close= ws.onclose = function(evt) {
  //   console.log("Connection closed.");
  // };
  return {
    open,
    message,
    friendMessage
  }
}
